package com.lhfeiyu.action.front.auction;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.lhfeiyu.config.Page;
import com.lhfeiyu.config.Tip;
import com.lhfeiyu.config.base.BaseTip;
import com.lhfeiyu.po.AuctionInst;
import com.lhfeiyu.po.base.BaseAnnouncement;
import com.lhfeiyu.po.base.BaseUser;
import com.lhfeiyu.po.base.BaseUserPraise;
import com.lhfeiyu.service.AuctionInstService;
import com.lhfeiyu.service.AuthCheckService;
import com.lhfeiyu.service.base.BaseAnnouncementService;
import com.lhfeiyu.service.base.BaseUserPraiseService;
import com.lhfeiyu.tools.base.ActionUtil;
import com.lhfeiyu.tools.base.CommonGenerator;
import com.lhfeiyu.tools.base.Result;
import com.lhfeiyu.util.base.RequestUtil;

/**
 * <strong> 描&nbsp;&nbsp;&nbsp;&nbsp;述：</strong> 控制层-前台：拍卖机构 AuctionInst <p>
 * <strong> 作&nbsp;&nbsp;&nbsp;&nbsp;者：</strong> 虞荣华 <p>
 * <strong> 编写时间：</strong> 2016年4月12日12:06:03 <p>
 * <strong> 公&nbsp;&nbsp;&nbsp;&nbsp;司：</strong> 成都蓝海飞鱼科技有限公司 http://lhfeiyu.com <p>
 * <strong> 版&nbsp;&nbsp;&nbsp;&nbsp;本：</strong> 2.0 <p>
 * <strong> 备&nbsp;&nbsp;&nbsp;&nbsp;注：</strong> 拍卖机构相关操作：拍卖机构，机构公告，机构点赞 <p>
 */
@Controller
@RequestMapping(value="/ap")
public class AuctionInstAction {
	@Autowired
	private AuctionInstService aiService;
	@Autowired
	private BaseAnnouncementService annoService;
	@Autowired
	private BaseUserPraiseService upService;
	@Autowired
	private AuthCheckService authCheckService;
	private static Logger logger = Logger.getLogger("R");
	
	@RequestMapping(value="/inst")
	public ModelAndView inst(ModelMap modelMap, HttpServletRequest request
			,@RequestParam(required=false) Integer shopId
			,@RequestParam(required=false) String r) {
		String path = Page.auctionInst;
		try{
			/*User sessionUser = ActionUtil.checkSession4User(session);
			if(null == sessionUser){
				String jumpUrl = "/auctionInst";
				if(null != shopId)jumpUrl = "/auctionInst?shopId="+shopId;
				return Result.userSessionInvalid(modelMap, jumpUrl);
			}*/
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, false, r);
			modelMap.put("shopId", shopId);
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/ap/inst", modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	
	@RequestMapping(value="/instApplyDesc")
	public ModelAndView instApplyDesc(ModelMap modelMap, HttpServletRequest request
			,@RequestParam(required=false) String r) {
		String path = Page.auctionInstApplyDesc;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, false, r);
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
			if(null == sessionUser){
				String jumpUrl = "/instApplyDesc";
				return Result.userSessionInvalid(modelMap, ActionUtil.buildPromoterUrl(jumpUrl, r));
			}
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/ap/instApplyDesc", modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	
	@RequestMapping(value="/instApply")
	public ModelAndView instApply(ModelMap modelMap, HttpServletRequest request
			,@RequestParam(required=false) String r) {
		String path = Page.auctionInstApply;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
			if(null == sessionUser){
				String jumpUrl = "/instApply";
				return Result.userSessionInvalid(modelMap, ActionUtil.buildPromoterUrl(jumpUrl, r));
			}
			Integer userId = sessionUser.getId();
			Map<String, Object> map = CommonGenerator.getHashMap();
			map.put("userId", userId);
			AuctionInst ai = aiService.selectByCondition(map);
			if(null != ai){
				modelMap.put("inst", ai);
				path = Page.myAuctionInst;
			}
			modelMap.put("username", sessionUser.getUsername());
			modelMap.put("phone", sessionUser.getPhone());
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/ap/instApply", modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	
	@RequestMapping(value="/myInst")
	public ModelAndView myInst(ModelMap modelMap, HttpServletRequest request
			,@RequestParam(required=false) String r) {
		String path = Page.myAuctionInst;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
			if(null == sessionUser){
				String jumpUrl = "/myInst";
				return Result.userSessionInvalid(modelMap, ActionUtil.buildPromoterUrl(jumpUrl, r));
			}
			Integer userId = sessionUser.getId();
			Map<String, Object> map = CommonGenerator.getHashMap();
			map.put("userId", userId);
			AuctionInst ai = aiService.selectByCondition(map);
			if(null != ai){
				modelMap.put("inst", ai);
			}else{
				path = Page.auctionInstApply;
			}
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/ap/myInst", modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	
	@RequestMapping(value="/instDesc/{instId}")
	public ModelAndView instDesc(ModelMap modelMap, HttpServletRequest request
			,@PathVariable Integer instId 
			,@RequestParam(required=false) String r) {
		String path = Page.instDesc;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
			AuctionInst inst = aiService.selectByPrimaryKey(instId);
			int instUserId = inst.getUserId();
			if(null != sessionUser){
				int userId = sessionUser.getId();
				if(userId == instUserId)modelMap.put("manager", 1);
			}
			modelMap.put("inst", inst);
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/ap/instDesc/"+instId, modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	
	@RequestMapping(value="/instDescUpdate/{instId}")
	public ModelAndView instDescUpdate(ModelMap modelMap, HttpServletRequest request
			,@PathVariable Integer instId
			,@RequestParam(required=false) String r) {
		String path = Page.instDesc;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			BaseUser user = ActionUtil.checkSession4User(request.getSession());
			if(null == user){
				String jumpUrl = "/instDescUpdate/"+instId;
				return Result.userSessionInvalid(modelMap, ActionUtil.buildPromoterUrl(jumpUrl, r));
			}
			AuctionInst inst = aiService.selectByPrimaryKey(instId);
			int instUserId = inst.getUserId();
			int userId = user.getId();
			if(userId == instUserId){
				modelMap.put("inst", inst);
				path = Page.instDescUpdate;
			}
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/ap/instDescUpdate/"+instId, modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	
	@RequestMapping(value="/instAnno/{instId}")
	public ModelAndView instAnno(ModelMap modelMap, HttpServletRequest request
			,@PathVariable Integer instId
			,@RequestParam(required=false) String r) {
		String path = Page.instAnno;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, false, r);
			BaseUser user = ActionUtil.checkSession4User(request.getSession());
			if(null == user){
				String jumpUrl = "/instAnno/"+instId;
				return Result.userSessionInvalid(modelMap, ActionUtil.buildPromoterUrl(jumpUrl, r));
			}
			Map<String, Object> map = RequestUtil.getRequestParam(request);//自动获取所有参数（查询条件）
			map.put("start", 0);
			map.put("count", 20);
			map.put("typeId", 102);//拍场公告
			map.put("linkId", instId);//在URL路径中获取的参数不为被自动获取，需要手动存入paramMap
			List<BaseAnnouncement> annoList = annoService.selectListByCondition(map);
			modelMap.put("annoList", annoList);
			AuctionInst inst = aiService.selectByPrimaryKey(instId);
			int instUserId = inst.getUserId();
			int userId = user.getId();
			if(instUserId == userId){
				modelMap.put("manager", 1);
				modelMap.put("inst", inst);
			}
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/ap/instAnno/"+instId, modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	
	@RequestMapping(value="/instAnnoDetail/{annoId}")
	public ModelAndView instAnnoDetail(ModelMap modelMap, HttpServletRequest request
			,@PathVariable Integer annoId
			,@RequestParam(required=false) String r) {
		String path = Page.commonBaseArtilce;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, false, r);
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
			if(null == sessionUser){
				String jumpUrl = "/instAnnoDetail/"+annoId;
				return Result.userSessionInvalid(modelMap, ActionUtil.buildPromoterUrl(jumpUrl, r));
			}
			BaseAnnouncement anno = annoService.selectByPrimaryKey(annoId);
			modelMap.put("article", anno);
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/ap/instAnnoDetail/"+annoId, modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	
	@RequestMapping(value="/instAnnoAddOrUpdate")
	public ModelAndView instAnnoAddOrUpdate(ModelMap modelMap, HttpServletRequest request
			,@RequestParam Integer instId
			,@RequestParam(required=false) Integer annoId
			,@RequestParam(required=false) String r) {
		String path = Page.instAnnoAddOrUpdate;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
			if(null == sessionUser){
				String jumpUrl = "/instAnnoAddOrUpdate="+instId;
				if(null != annoId)jumpUrl += "?annoId="+annoId;
				return Result.userSessionInvalid(modelMap, ActionUtil.buildPromoterUrl(jumpUrl, r));
			}
			if(null != annoId){
				BaseAnnouncement anno = annoService.selectByPrimaryKey(annoId);
				modelMap.put("anno", anno);
			}
			modelMap.put("instId", instId);
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/ap/instAnnoAddOrUpdate/"+instId, modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	
	@ResponseBody
	@RequestMapping(value="/getAuctionInstList", method=RequestMethod.POST)
	public JSONObject getAuctionInstList(HttpServletRequest request) {
		JSONObject json = new JSONObject();
		try {
			Map<String, Object> map = ActionUtil.getAllParam(request);
			aiService.getAuctionInstList(json, map);
		} catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName()+"/ap/getAuctionInstList", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/getMyAuctionInst", method=RequestMethod.POST)
	public JSONObject getMyAuctionInst(HttpServletRequest request) {
		JSONObject json = new JSONObject();
		try {
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == sessionUser){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			Integer userId = sessionUser.getId();
			Map<String, Object> map = CommonGenerator.getHashMap();
			map.put("userId", userId);
			AuctionInst ai = aiService.selectByCondition(map);
			if(null != ai){
				json.put("auctionInst", ai);
			}else{
				Result.failure(json, Tip.msg_auctionInst_null, Tip.code_auctionInst_null);
			}
		} catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName()+"/ap/getMyAuctionInst", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/updateAuctionInst", method=RequestMethod.POST)
	public JSONObject updateAuctionInst(@ModelAttribute AuctionInst auctionInst, HttpServletRequest request){
		JSONObject json = new JSONObject();
		try {
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == sessionUser){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			Integer instId = auctionInst.getId();
			if(null == instId){
				return Result.failure(json, Tip.msg_auctionInstId_null, Tip.code_auctionInstId_null);
			}
			AuctionInst inst = aiService.selectByPrimaryKey(instId);
			int instUserId = inst.getUserId();
			int userId = sessionUser.getId();
			if(userId != instUserId){
				return Result.failure(json, BaseTip.msg_auth_lack, BaseTip.code_auth_lack);
			}
			AuctionInst ai = new AuctionInst();
			ai.setId(auctionInst.getId());
			ai.setName(auctionInst.getName());
			ai.setAddress(auctionInst.getAddress());
			ai.setTel(auctionInst.getTel());
			ai.setPicPaths(auctionInst.getPicPaths());
			ai.setIntroduce(auctionInst.getIntroduce());
			ai.setUpdatedAt(new Date());
			ai.setUpdatedBy(sessionUser.getUsername());
			aiService.updateByPrimaryKeySelective(ai);
		}catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName()+"/ap/updateAuctionInst", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/addOrUpdateInstAnno", method=RequestMethod.POST)
	public JSONObject addOrUpdateInstAnno(@ModelAttribute BaseAnnouncement announcement, HttpServletRequest request){
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			int userId = user.getId();
			Integer instId = announcement.getLinkId();
			if(null == instId){
				return Result.failure(json, Tip.msg_auctionInstId_null, Tip.code_auctionInstId_null);
			}
			Integer annoId = announcement.getId();
			AuctionInst inst = aiService.selectByPrimaryKey(instId);
			int instUserId = inst.getUserId();
			if(null == annoId){//新增
				if(userId != instUserId){
					return Result.failure(json, BaseTip.msg_auth_lack, BaseTip.code_auth_lack);
				}
				BaseAnnouncement anno = new BaseAnnouncement();
				anno.setTypeId(102);//102:拍场公告
				anno.setLinkId(instId);
				anno.setUserId(userId);
				anno.setTitle(announcement.getTitle());;
				anno.setDescription(announcement.getDescription());
				anno.setContent(announcement.getContent());
				anno.setCreatedAt(new Date());
				anno.setCreatedBy(user.getUsername());
				annoService.insert(anno);
			}else{//修改
				BaseAnnouncement oldAnno = annoService.selectByPrimaryKey(annoId);
				int oldUserId = oldAnno.getUserId();
				if(userId != oldUserId){
					return Result.failure(json, BaseTip.msg_auth_lack, BaseTip.code_auth_lack);
				}
				BaseAnnouncement anno = new BaseAnnouncement();
				anno.setId(annoId);
				anno.setTitle(announcement.getTitle());;
				anno.setContent(announcement.getContent());
				anno.setUpdatedAt(new Date());
				anno.setUpdatedBy(user.getUsername());
				annoService.updateByPrimaryKeySelective(anno);
			}
		}catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName()+"/ap/addOrUpdateInstAnno", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/deleteInstAnno", method=RequestMethod.POST)
	public JSONObject deleteInstAnno(HttpServletRequest request, @RequestParam Integer annoId){
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			BaseAnnouncement  anno = annoService.selectByPrimaryKey(annoId);
			int annoUserId = anno.getUserId();
			int userId = user.getId();
			if(userId != annoUserId){
				return Result.failure(json, BaseTip.msg_auth_lack, BaseTip.code_auth_lack);
			}
			annoService.deleteByPrimaryKey(annoId);
		}catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName()+"/ap/deleteInstAnno", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/addPraiseForInst", method=RequestMethod.POST)
	public JSONObject addPraiseForInst(HttpServletRequest request, @RequestParam Integer instId){
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			Integer userId = user.getId();
			Map<String, Object> map = CommonGenerator.getHashMap();
			map.put("praiseType", 1);
			map.put("praiseId", instId);
			map.put("userId", userId);
			int count = upService.selectCountByCondition(map);
			if(count > 0){
				return Result.failure(json, Tip.msg_userPraise_repeat, Tip.code_userPraise_repeat);
			}else{
				BaseUserPraise up = new BaseUserPraise();
				up.setPraiseType(1);//拍卖机构
				up.setPraiseId(instId);
				up.setUserId(userId);
				up.setCreatedAt(new Date());
				up.setCreatedBy(user.getUsername());
				upService.insert(up);
			}
		}catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName()+"/ap/addPraiseForInst", json);
		}
		return Result.success(json);
	}
}
